package com.base.cn.platform.os.controller.mobile.user.login;

import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.base.cn.platform.os.service.manage.user.login.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 用户登录工具对象
 *
 * @author s.li
 * @create 2018-08-31-14:00
 */
@Component
public class LoginUserData {

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 设置用户登录缓存数据
     * @param request
     * @param response
     * @param resultMap
     */
    public Map<String,Object> setUserData(HttpServletRequest request,
                                           HttpServletResponse response, Map<String,Object> resultMap){
        if(ResultUtil.getSuccess(resultMap)==true){
            String sessionId = (String)resultMap.get("sessionId");
            String status = (String)resultMap.get("status");
            //是否设置登录密码
            boolean administrator = resultMap.get("administrator")==null?false:(boolean)resultMap.get("administrator");
            //需要完善资料
            if(StringUtils.isNotEmpty(status) && status.equals("MOBILE")){
                //设置完善资料
                resultMap.put("url","/mobile/user/perfectMobile?key="+sessionId);
            }else{
                //定制专业科目
                if(StringUtils.isNotEmpty(status) && status.equals("SUBJECT")){
                    resultMap.put("url","/mobile/user/perfectSubject?key="+sessionId);
                }else{
                    Map<String,Object> user = (Map<String,Object>)ResultUtil.getEntity(resultMap);
                    //如果有登录未退出
                    String oldSessionId = WebUtils.getCookie(request, CommonConstants.MOBILE_USER_SINGLE_ID);
                    if(StringUtils.isNotEmpty(oldSessionId)){
                        //退出原来的登录
                        boolean isOk = userLoginService.signOut(oldSessionId,new BigDecimal(user.get("id").toString()));
                        if(isOk){
                            //删除COOKIE缓存
                            WebUtils.deleteCookie(request,response,oldSessionId);
                        }
                    }
                    //缓存一天
                    WebUtils.setCookie(response,CommonConstants.MOBILE_USER_SINGLE_ID,sessionId,1);
                    if(administrator){
                        resultMap.put("url","/mobile/uc/administratorPwd");
                    }
                }
            }
            ResultUtil.setEntity(resultMap,null);
        }
        return resultMap;
    }
}
